package org.casaca.checkbackup.core.task;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.casaca.checkbackup.core.data.Backup;
import org.casaca.checkbackup.core.data.Folder;

public class FileCollector extends Task {
	
	private Backup backup;
	private boolean backupFilledFlag;
	private List<FileCollectorListener> listeners;
	
	public FileCollector(){
		this.backup = null;
		this.backupFilledFlag = false;
		this.listeners = new ArrayList<FileCollectorListener>();
	}
	
	private void fill(Folder folder){
		File file = new File(folder.getPath());
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if(files[i].isFile()){
				org.casaca.checkbackup.core.data.File file2 = new org.casaca.checkbackup.core.data.File(folder, files[i].getName());
				folder.getChildren().add(file2);
				this.notifyFile(file2);
			}
			else if(files[i].isDirectory()){
				Folder folder2 = new Folder(folder, files[i].getName());
				this.notifyFolder(folder2);
				this.fill(folder2);
				folder.getChildren().add(folder2);
			}
		}
	}

	@Override
	public void run() {
		Folder originalFolder = this.backup.getOriginalFolder();
		fill(originalFolder);
		Folder backupFolder = this.backup.getBackupFolder();
		fill(backupFolder);
		this.backupFilledFlag = true;
		this.notifyCollectedCompleted();
	}
	
	public void setBackup(Backup backup){
		this.backup = backup;
		this.backupFilledFlag = false;
	}

	public Backup getBackup(){
		if(this.backup==null)
			throw new IllegalStateException("Backup is null");
		
		if(!this.backupFilledFlag)
			throw new IllegalStateException("Execute the task before getting the backup");
		
		return this.backup;
	}
	
	public void addListener(FileCollectorListener listener){
		this.listeners.add(listener);
	}
	
	public void removeListener(FileCollectorListener listener){
		this.listeners.remove(listener);
	}
	
	private void notifyFile(org.casaca.checkbackup.core.data.File file){
		for (FileCollectorListener listener : this.listeners) {
			listener.fileCollected(file);
		}
	}
	
	private void notifyFolder(Folder folder){
		for (FileCollectorListener listener : this.listeners) {
			listener.folderCollected(folder);
		}
	}
	
	private void notifyCollectedCompleted(){
		for (FileCollectorListener listener : this.listeners) {
			listener.collectionCompleted();
		}
	}
}